package com.bwie.system.task;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.expression.engine.aviator.AviatorEngine;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bwie.common.constants.Constants;
import com.bwie.common.domain.RedPacket;
import com.bwie.common.domain.User;
import com.bwie.system.init.InitSnatchMsgToEs;
import com.bwie.system.service.RedPacketService;
import com.bwie.system.service.UserService;
import com.bwie.system.utils.SendSmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author Junchen_N1
 * @Date 2025/6/17 15:33
 * @ClassName SystemTask
 * @Description TODO
 */
@Component
public class SystemTask {

    @Autowired
    private RedPacketService redPacketService;

    @Autowired
    private UserService userService;

    @Autowired
    private InitSnatchMsgToEs initSnatchMsgToEs;

    @Autowired
    private SendSmsUtils sendSmsUtils;

    @Scheduled(cron = "0/10 * * * * ?")
    public void updateRedPacketStatus(){
        List<RedPacket> redPacketList = redPacketService.selectAllWhereStatusIs0();
        //判断是否过期
        redPacketList.forEach(item->{
            long betweenMinutes = DateUtil.between(item.getSendTime(), new Date(), DateUnit.MINUTE);
            if (betweenMinutes>item.getContinuousMinutes()){
                LambdaUpdateWrapper<RedPacket> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.eq(RedPacket::getRedPacketId,item.getRedPacketId());
                updateWrapper.set(RedPacket::getRedPacketStatus,1);
                redPacketService.update(updateWrapper);
                //如果有未领取的金额，退回原账户
                if (item.getRedPacketRemainPrice().compareTo(new BigDecimal(BigInteger.ZERO))>0){
                    userService.updateUserBalance(item.getSenderId(),item.getRedPacketRemainPrice(), Constants.ADD_BALANCE);
                    //获取用户信息
                    User userServiceById = userService.findById(item.getSenderId());
                    //发送消息
                    sendSmsUtils.sendSms(userServiceById.getTel(), JSON.toJSONString(new HashMap<String,String>(){{
                        put("code","您在【"+item.getSendTime()+"】发送的红包【"+item.getRedPacketName()+"】，总金额【"+item.
                                getRedPacketPrice()+"】，还剩余【"+item.getRedPacketRemainPrice()+"】现已全部退回");
                    }}));

                }

            }
        });
    }

    @Scheduled(cron = "0 0/10 * * * ?")
    public void getSnatchMsgFromSQLToEs(){
        initSnatchMsgToEs.initSnatchMsgToEs();
    }
}
